package com.liu.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.liu.sunnyday.constant.MessageConstant;
import com.liu.sunnyday.entity.Result;
import com.liu.sunnyday.service.MemberService;
import com.liu.sunnyday.service.ReportService;
import com.liu.sunnyday.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * chance！Time
 *
 * @author liuqian
 * @date 2022-07-08 16:24
 * *
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     *
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        // 组装过去12个月的数据, 前端是一个数组
        List<String> months = new ArrayList<String>();
        // 使用java中的calendar来操作日期, 日历对象
        Calendar calendar = Calendar.getInstance();
        // 设置过去一年的时间  年-月-日 时:分:秒, 减去12个月
        calendar.add(Calendar.YEAR, -1);
        // 构建12个月的数据
        for (int i = 0; i < 12; i++) {
            try {
                // 每次增加一个月就
                calendar.add(Calendar.MONTH, 1);
                // 过去的日期, 设置好的日期
                Date date = calendar.getTime();
                // 转换成我们数据库可以使用的'yyyy-MM-dd'字符串
                String dateString = DateUtils.parseDate2String(date);
                //添加组拼好的过去12个月的月份到List集合
                months.add(dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 调用服务查询过去12个月会员数据 前端也是一数组 数值
        List<Integer> memberCount = memberService.getMemberReport(months);
        // 放入map
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("months", months);
        resultMap.put("memberCount", memberCount);

        // 再返回给前端
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //1.调用服务查询套餐预约占比,只需要查出它，它包含了前端页面需要的套餐名称集合
        List<Map<String, Object>> setmealCount = memberService.getSetmealReport();
        //2.抽取套餐名称集合
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> map : setmealCount) {
            // {value:222,name:xx套餐}
            // null.toString()  (String)null
            String setmealName = (String) map.get("name");
            setmealNames.add(setmealName);
        }
        //3.封装结果返回给页面
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("setmealNames", setmealNames);
        resultMap.put("setmealCount", setmealCount);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, resultMap);
        //List<Map<String,Object>> list = memberService.getSetmealReport();
        //
        //Map<String,Object> map1=new HashMap<String,Object>();
        //List<String> setmealNames = null;
        //List<Object> setmealCount = null;
        //
        //for (Map<String, Object> map : list) {
        //    setmealNames.add((String) map.get("name"));
        //    map1.put("setmealNames",setmealNames);
        //    setmealCount.add(map.get("num"));
        //    map1.put("setmealCount",setmealCount);
        //}
        //return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL, map1);
    }

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        System.out.println("运营数据统计进来了查询");
        Map<String, Object> businessReport = reportService.getBusinessReportData();
        System.out.println(businessReport);
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, businessReport);
    }

    /**
     * 上传excel表（运营统计数据报表）
     * 导出
     *
     * @return
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res) {
        //获取运营统计数据
        Map<String, Object> businessReport = reportService.getBusinessReportData();
        //获取模板路径(提前放在webapp的template下如：report_template.xlsx)
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        try {
            //创建工作薄（模板路径）
            FileInputStream fis = new FileInputStream(template);
            OutputStream os = res.getOutputStream();
            XSSFWorkbook wk = new XSSFWorkbook(fis);


            //    获取工作表
            XSSFSheet sht = wk.getSheetAt(0);
            //日期坐标2，5(就是目标格式表中需要天地数据坐标，横轴数轴都是索引从0开始)
            //(2,5)的意思就是第三行的第六列
            sht.getRow(2).getCell(5).setCellValue(businessReport.get("reportDate").toString());
            // 今日新增会员数
            sht.getRow(4).getCell(5).setCellValue(businessReport.get("todayNewMember").toString());
            //总会员数
            sht.getRow(4).getCell(7).setCellValue(businessReport.get("totalMember").toString());
            // 本周新增会员数
            sht.getRow(5).getCell(5).setCellValue(businessReport.get("thisWeekNewMember").toString());
            //本月新增会员数
            sht.getRow(5).getCell(7).setCellValue(businessReport.get("thisMonthNewMember").toString());

            // 今日预约数
            sht.getRow(7).getCell(5).setCellValue(businessReport.get("todayOrderNumber").toString());
            //今日到诊数
            sht.getRow(7).getCell(7).setCellValue(businessReport.get("todayVisitsNumber").toString());
            // 本周预约数
            sht.getRow(8).getCell(5).setCellValue(businessReport.get("thisWeekOrderNumber").toString());
            //本周到诊数
            sht.getRow(8).getCell(7).setCellValue(businessReport.get("thisWeekVisitsNumber").toString());
            // 本月预约数
            sht.getRow(9).getCell(5).setCellValue(businessReport.get("thisMonthOrderNumber").toString());
            //本月到诊数
            sht.getRow(9).getCell(7).setCellValue(businessReport.get("thisMonthVisitsNumber").toString());


            //热门套餐,初始化行数为12
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) businessReport.get("hotSetmeal");
            int row = 12;
            for (Map<String, Object> map : hotSetmeal) {
                sht.getRow(row).getCell(4).setCellValue((String) map.get("name"));
                sht.getRow(row).getCell(5).setCellValue((long) map.get("setmeal_count"));

                BigDecimal proportion = (BigDecimal) map.get("proportion");
                sht.getRow(row).getCell(6).setCellValue(proportion.doubleValue());
                sht.getRow(row).getCell(7).setCellValue((String) map.get("remark"));
                row++;
            }
            String filename = "运营统计数据表.xlsx";
            //解决下载文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");

            //设置头信息，告诉浏览器，是带附件的文件下载
            res.setHeader("Content-Disposition", "attachement;filename=" + filename);
            //设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            wk.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

